package com.ai.study.dashscope.controller.prompt;

import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplate;
import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplateFactory;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.chat.prompt.SystemPromptTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;
import java.util.Map;

/**
 * @Author chenwei
 * @Date 2025/6/29 20:22
 */
@RestController
@RequestMapping("/dashscope/example/ai/prompt/template")
@Tag(name = "prompt template 测试")
public class PromptTemplateController {

    private final ChatClient dashScopeChatClient;

    private final ConfigurablePromptTemplateFactory configurablePromptTemplateFactory;

    public PromptTemplateController(
                    @Qualifier("dashScopeChatClient") ChatClient dashScopeChatClient,
                    ConfigurablePromptTemplateFactory configurablePromptTemplateFactory) {
        this.dashScopeChatClient = dashScopeChatClient;
        this.configurablePromptTemplateFactory = configurablePromptTemplateFactory;
    }

    @GetMapping("/chat")
    @Operation(summary = "根据提示词模版，来进行问话")
    public AssistantMessage generate(
            @RequestParam(value = "author", required = false, defaultValue = "Bob") String author
    ) {

        ConfigurablePromptTemplate template = configurablePromptTemplateFactory.getTemplate("test-template");

        if (template == null) {
            template = configurablePromptTemplateFactory.create("test-template",
                    "请列出 {anthor} 最著名的三本书。");
        }

        Prompt prompt;

        if (StringUtils.hasText(author)) {
            prompt = template.create(Map.of("anthor", author));
        } else {
            prompt = template.create();
        }

        return dashScopeChatClient.prompt(prompt)
                .call()
                .chatResponse()
                .getResult()
                .getOutput();
    }
}